package com.changgou.web.order.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.pay.feign.PayFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/wxpay")
public class PayController {

    @Autowired
    private PayFeign payFeign;

    @Autowired
    private OrderFeign orderFeign;

    // 跳转到支付二维码页面
    @GetMapping
    public String wxPay(String orderId, Model model){

        // 1.根据orderId查询订单，如果不存在，跳转到错误页面
        Order order = orderFeign.findById(orderId).getData();
        if (order == null){
            return "fail";
        }
        // 2.根据订单支付状态判断，如果不是未支付，则跳转到错误页面
        String orderStatus = order.getOrderStatus();
        if (!"0".equals(orderStatus)){
            return "fail";
        }
        // 3.基于feign接口调用，得到结果数据
        Integer money = order.getPayMoney();
        Result result = payFeign.nativePay(orderId, money);

        if (result.getData() == null){
            return "fail";
        }
        // 4.封装结果数据
        Map map = (Map) result.getData();
        map.put("orderId",orderId);
        map.put("payMoney",order.getPayMoney());

        model.addAllAttributes(map);
        return "wxpay";
    }

}
